//
//  NetAPIClient.m
//  Normal
//
//  Created by 8b410-2 on 16/12/9.
//  Copyright © 2016年 abb. All rights reserved.
//

#import "NetAPIClient.h"
#define kNetworkMethodName @[@"Get", @"Post"]
@implementation NetAPIClient
static NetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;

+ (NetAPIClient *)shareJsonClient {
    dispatch_once(&onceToken,^{
        _sharedClient = [[NetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURLStr]];
    });
    return _sharedClient;
}

+ (id)changeJsonClient {
    _sharedClient = [[NetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURLStr]];
    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    self.securityPolicy.allowInvalidCertificates = YES;
    return  self;
}
#pragma 网络请求
- (void)requestJsonDataWithParams:(NSDictionary *)params
                   withMethodType:(NetworkMethod)method
                         andBlock:(void (^)(NSDictionary *dict, NSError *))block {
    [self requestJsonDataWithParams:params
                     withMethodType:method
                   AndHudShowOption:HudShowOptionShowErrorHud|HudShowOptionShowSuccessHud|HudShowOptionShowWaitHud
                           andBlock:block];
}
- (void)requestJsonDataWithParams:(NSDictionary *)params
                   withMethodType:(NetworkMethod)method
                 AndHudShowOption:(HudShowOption)option
                         andBlock:(void (^)(NSDictionary *dict, NSError *error))block{
    
    NSString *path = kUrlPath;
    NSDictionary *newParams = [self packageParams:params];
    if (option & HudShowOptionShowWaitHud) {
        // TODO: - 提示等待
    }
    DebugLog(@"\n=============request=============\n%@\n%@:\n%@",kNetworkMethodName[method],path,newParams);
    switch (method) {
            case Get:
            
            break;
            case Post:
            [self POST:path parameters:newParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (option & HudShowOptionShowWaitHud) {
                    // TODO: - 隐藏hud
                }
                DebugLog(@"\n=============response=============\n%@:\n%@",path,responseObject);
                // 服务器无返回时
                if (responseObject == [NSNull null]) {
                    NSError *error = [NSError errorWithDomain:kBaseURLStr code:-1000 userInfo:@{@"msg" : @"服务器出错啦"}];
                    // TODO: - 网络错误提示
                    block(nil,error);
                }
                // 解包判断有无错误
                id error = [self handleResponse:responseObject autoShowError:(option & HudShowOptionShowErrorHud)];
                if (error) {
                    block(nil,error);
                } else {
                    // 无错误返回成功
                    NSString *successStr = [(NSDictionary *)responseObject valueForKey:@"msg"];
                    if (option & HudShowOptionShowSuccessHud) {
                        // TODO: - 成功提示
                    }
                    block(responseObject,nil);
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                // TODO: - 隐藏hud
                DebugLog(@"\n===========response===========\n%@:\n%@", path, error);
                if (option & HudShowOptionShowErrorHud){
                    // TODO: - 网络错误提示
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationNetError object:nil];
                block(nil,error);
            }];
    }
}
- (void)requestUploadImageWithPath:(NSString *)path
                              Name:(NSString *)name
                            Params:(NSDictionary *)params
                        ImageArray:(NSArray *)imageArray
                          AndBlock:(void (^)(NSDictionary *dict, NSError *))block{
    NSDictionary *newParams = [self packageParams:params];
    NSLog(@"%@",[NSThread currentThread]);
    DebugLog(@"\n=============request=============\n%@:\n%@",path,newParams);
    // TODO: - 提示等待
    [self POST:path parameters:newParams constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *image in imageArray) {
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data name:name fileName:@"1.png" mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // TODO: - 进度提示
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // TODO: - 隐藏hud
        DebugLog(@"\n=============response=============\n%@:\n%@",path,responseObject);
        id error = [self handleResponse:responseObject];
        if (error) {
            block(nil,error);
        } else {
            NSString *successStr = [(NSDictionary *)responseObject valueForKey:@"msg"];
            // TODO: - 成功提示
            block(responseObject,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DebugLog(@"\n===========response===========\n%@:\n%@", path, error);
        // TODO: - 网络错误提示
        block(nil,error);
    }];
    
    
}
#pragma mark - 参数处理
/**
 打包参数
 
 @param params 需要处理的参数
 @return 处理好的参数
 */
- (NSDictionary *)packageParams:(NSDictionary *)params {

    NSMutableDictionary *newParams = [params mutableCopy];

    return newParams;
}

#pragma mark - 网络监测

static BOOL _networkReachability;

+ (void)openNetworkCheckReachability{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
                case AFNetworkReachabilityStatusReachableViaWiFi:
                case AFNetworkReachabilityStatusReachableViaWWAN:
                _networkReachability = YES;
                break;
            default:
                _networkReachability = NO;
                break;
        }
    }];
}
#pragma mark - NetError
- (id)handleResponse:(id)responseJSON {
    return [self handleResponse:responseJSON autoShowError:YES];
}

- (id)handleResponse:(id)responseJSON autoShowError:(BOOL)autoShowError {
    NSError *error = nil;
    return error;
}

@end
